//
//  DataBaseHandle.m
//  PTravel
//
//  Created by dllo on 15/11/28.
//  Copyright © 2015年 李涵. All rights reserved.
//

#import "DataBaseHandle.h"

@implementation DataBaseHandle

+ (instancetype)shareDataBase
{
    static DataBaseHandle *dataBaseHandle = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dataBaseHandle = [[DataBaseHandle alloc] init];
        [dataBaseHandle openDB];
    });
    return dataBaseHandle;
    
}
#pragma mark === 打开数据库
- (void)openDB
{
    //导入sqlite框架，导入FMDB文件夹
    //1.获得数据库文件的路径
    NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *fileName=[doc stringByAppendingPathComponent:@"travel.sqlite"];
    NSLog(@"数据库表的路径: fileName ===== %@",fileName);
    
    //2.获得数据库
    self.db = [FMDatabase databaseWithPath:fileName];
    if ([self.db open]) {
        NSLog(@"打开数据库成功");
    }else{
        NSLog(@"打开数据失败");
    }
    
}

#pragma mark === 创建表
//创建表
-(void)createTableSql:(NSString *)sql
{
    BOOL result = [self.db executeUpdate:sql];
    if (result) {
        NSLog(@"创建表成功");
    }else{
        NSLog(@"创建表失败");
    }
}


#pragma mark === 插入数据
//插入数据
-(void)insertData:(NSString *)sql
{
    BOOL result = [self.db executeUpdate:sql];
    if (result) {
        NSLog(@"插入成功");
    }else{
        NSLog(@"插入失败");
    }
}

//查询数据
-(NSMutableArray *)selectDataTableSql:(NSString *)sql
{
    NSMutableArray *arr = [NSMutableArray array];
    FMResultSet *resultSet = [self.db executeQuery:sql];
    while ([resultSet next]) {
        NSString *country_id = [resultSet objectForColumnName:@"country_id"];
        NSString *cnname = [resultSet objectForColumnName:@"cnname"];
        Country *country = [[Country alloc] init];
        country.cnname = cnname;
        country.id = country_id.intValue;
        [arr addObject:country];
    }
    return  arr;
}
//查询抢折扣
-(NSMutableArray *)selectDiscountSql:(NSString *)sql
{
    NSMutableArray *arr = [NSMutableArray array];
    FMResultSet *resultSet = [self.db executeQuery:sql];
    while ([resultSet next]) {
        NSString *url = [resultSet objectForColumnName:@"url"];
        NSString *titleName = [resultSet objectForColumnName:@"titleName"];
        WebDiscount *dis = [[WebDiscount alloc] init];
        dis.url = url;
        dis.titleName = titleName;
        [arr addObject:dis];
    }
    return  arr;
}

#pragma mark === 删除表
//删除表
-(void)dropTableDropSql:(NSString *)DropSql CreateSql:(NSString *)CreateSql
{
    
}

#pragma mark === 删除表数据
//删除
-(void)deleteDataTableSql:(NSString *)deleteSql
{
    BOOL result = [self.db executeUpdate:deleteSql];
    if (result) {
        NSLog(@"删除成功");
    }else{
        NSLog(@"删除失败");
    }

}
@end
